package com.ayu.commentbackend.handler;

import com.ayu.commentbackend.pojo.result.Result;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

// 全局异常处理类
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        e.printStackTrace();
        return Result.error(StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "操作失败");
    }
    @ExceptionHandler
    public Result handleException(DuplicateKeyException ex) {
        // Duplicate entry 'admin' for key 'user.unique_username'
        String message = ex.getCause().getMessage();
        if(message.contains("Duplicate entry")){
            String duplicateEntryName = message.split(" ")[2];
            return Result.error(duplicateEntryName+"已存在");
        }
        else {
            return Result.error(message);
        }
    }
}
